<?php
class ControllerSaleLuckydraw extends Controller {
  private $error = array();
  private $filter_keys = array(
    'filter_luckydraw_name'=>array('need_encode'=>1, 'default_value'=>null),
    'filter_status'=>array('need_encode'=>0, 'default_value'=>null)
    );

  public function baseBuildUrlPath() {
    $url = '';

    foreach ($this->filter_keys as $key => $attr) {
      if (isset($this->request->get[$key])) {
        if($attr['need_encode']) {
          $url .= '&' . $key . '=' . urlencode(html_entity_decode($this->request->get[$key], ENT_QUOTES, 'UTF-8'));
        } else {
          $url .= '&' . $key . '=' . $this->request->get[$key];
        }
      }  
    }
    
    return $url;
  }

  function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
  }

  public function buildUrlPath($include_page=true) {
    $url = $this->baseBuildUrlPath();

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }
    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }
    if ($include_page&&isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    return $url;
  }


  public function index() {
    $this->load->language('sale/luckydraw');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('sale/luckydraw');

    $this->getList();
  }

  public function add() {
    $this->load->language('sale/luckydraw');

    $this->document->setTitle($this->language->get('heading_title'));
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/luckydraw.js');

    $this->load->model('sale/luckydraw');
    $this->load->model('catalog/product');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $luckydraw_id = $this->model_sale_luckydraw->addLuckydraw($this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      $url = $this->buildUrlPath();

      $this->response->redirect($this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function edit() {
    $this->load->language('sale/luckydraw');

    $this->document->setTitle($this->language->get('heading_title'));
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/luckydraw.js');

    $this->load->model('sale/luckydraw');
    $this->load->model('catalog/product');

    $this->getForm();
  }

  public function delete() {
    $this->load->language('sale/luckydraw');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('sale/luckydraw');

    if (isset($this->request->post['selected']) && $this->validateDelete()) {
      foreach ($this->request->post['selected'] as $luckydraw_id) {
        $this->model_sale_luckydraw->deleteLuckydraw($luckydraw_id);
      }

      $this->session->data['success'] = $this->language->get('text_success');

      $url = $this->buildUrlPath();

      $this->response->redirect($this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/luckydraw');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      $json = array();
      if (!$this->user->hasPermission('modify', 'sale/luckydraw')) {
        $json['error'] = '您没有权限修改幸运抽奖';
      }
      //抽奖名称、状态、开始时间、结束时间是否为空
      if(!isset($json['error'])) {
        $empty_check = array('luckydraw_name'=>'幸运抽奖名称', 'status'=>'状态', 'start_time'=>'开始时间', 'end_time'=>'结束时间');
        foreach ($empty_check as $key => $msg) {
          if(!isset($data[$key])) {
            $json['error'] = '请输入' . $msg;
          }
        }  
      }
      //开始时间结束时间是否为合法时间
      if(!isset($json['error'])) {
        if(!$this->validateDate($data['start_time'])) {
            $json['error'] = '开始时间格式错误';
        }
        if(!$this->validateDate($data['end_time'])) {
            $json['error'] = '结束时间格式错误';
        }
      }
      //抽奖概率是否在1-100之间
      if(!isset($json['error'])) {
        $data['chance'] = (float)$data['chance'];
        if($data['chance']>100||$data['chance']<1) {
          $json['error'] = '中奖概率需要为1到100之间';
        }
      }
      //产品是否为空
      //抽奖次数是否为空
      //添加幸运抽奖
      if(!isset($json['error'])) {
        if($data['is_edit']) {
          $this->model_sale_luckydraw->editLuckydraw($data);  
        } else {
          $luckydraw_id = $this->model_sale_luckydraw->addLuckydraw($data);
        }
      }

      if(!isset($json['error'])) {
        $json['success'] = true;
      } else {
        $json['success'] = false;
      }

      $this->response->addHeader('Content-Type: application/json');
      $this->response->setOutput(json_encode($json));
      return;
    }
  }


  protected function getList() {
    $filter_data_orig = array();
    foreach ($this->filter_keys as $key => $attr) {
      if (isset($this->request->get[$key])) {
        $filter_data_orig[$key] = $this->request->get[$key];
      } else {
        $filter_data_orig[$key] = null;
      }
    }

    if (isset($this->request->get['sort'])) {
      $sort = $this->request->get['sort'];
    } else {
      $sort = 'luckydraw_id';
    }

    if (isset($this->request->get['order'])) {
      $order = $this->request->get['order'];
    } else {
      $order = 'DESC';
    }

    if (isset($this->request->get['page'])) {
      $page = $this->request->get['page'];
    } else {
      $page = 1;
    }

    $url = $this->buildUrlPath();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('heading_title'),
      'href' => $this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL')
    );

    $data['add'] = $this->url->link('sale/luckydraw/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $data['delete'] = $this->url->link('sale/luckydraw/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

    $data['luckydraws'] = array();

    $filter_data = array(
      'sort'            => $sort,
      'order'           => $order,
      'start'           => ($page - 1) * $this->config->get('config_limit_admin'),
      'limit'           => $this->config->get('config_limit_admin')
    );
    $filter_data = array_merge($filter_data_orig, $filter_data);

    $statuses = $this->model_sale_luckydraw->getLuckydrawStatusMap();
    $data['statuses'] = $statuses;

    $luckydraw_total = $this->model_sale_luckydraw->getTotalLuckydraws($filter_data);

    $results = $this->model_sale_luckydraw->getLuckydraws($filter_data);

    foreach ($results as $result) {
      $data['luckydraws'][] = array(
        'luckydraw_id' => $result['luckydraw_id'],
        'luckydraw_name' => $result['luckydraw_name'],
        'chance' => $result['chance'],
        'start_time' => $result['start_time'],
        'end_time' => $result['end_time'],
        'status' => $statuses[$result['status']],
        'edit'       => $this->url->link('sale/luckydraw/edit', 'token=' . $this->session->data['token'] . '&luckydraw_id=' . $result['luckydraw_id'] . $url, 'SSL')
      );
    }

    $data['heading_title'] = $this->language->get('heading_title');
    
    $data['text_list'] = $this->language->get('text_list');
    $data['text_enabled'] = $this->language->get('text_enabled');
    $data['text_disabled'] = $this->language->get('text_disabled');
    $data['text_no_results'] = $this->language->get('text_no_results');
    $data['text_confirm'] = $this->language->get('text_confirm');

    $data['column_image'] = $this->language->get('column_image');
    $data['column_name'] = $this->language->get('column_name');
    $data['column_model'] = $this->language->get('column_model');
    $data['column_price'] = $this->language->get('column_price');
    $data['column_quantity'] = $this->language->get('column_quantity');
    $data['column_status'] = $this->language->get('column_status');
    $data['column_action'] = $this->language->get('column_action');

    $data['entry_name'] = $this->language->get('entry_name');
    $data['entry_quantity'] = $this->language->get('entry_quantity');
    $data['entry_status'] = $this->language->get('entry_status');

    $data['button_copy'] = $this->language->get('button_copy');
    $data['button_add'] = $this->language->get('button_add');
    $data['button_edit'] = $this->language->get('button_edit');
    $data['button_delete'] = $this->language->get('button_delete');
    $data['button_filter'] = $this->language->get('button_filter');

    $data['token'] = $this->session->data['token'];

    if (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    if (isset($this->request->post['selected'])) {
      $data['selected'] = (array)$this->request->post['selected'];
    } else {
      $data['selected'] = array();
    }

    $url = $this->baseBuildUrlPath();

    if ($order == 'ASC') {
      $url .= '&order=DESC';
    } else {
      $url .= '&order=ASC';
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    $sort_keys = array('luckydraw_id' => 'luckydraw_id',
        'luckydraw_name' => 'luckydraw_name',
        'btb_order_id' => 'btb_order_id',
        'url_code' => 'url_code',
        'validate_method' => 'validate_method',
        'status' => 'status',
        );
    foreach ($sort_keys as $key => $sv) {
      $data['sort_'.$key] = $this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . '&sort=' . $sv . $url, 'SSL');
    }

    $url = $this->buildUrlPath(false);

    $pagination = new Pagination();
    $pagination->total = $luckydraw_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
    
    $data['pagination'] = $pagination->render();

    $data['results'] = sprintf($this->language->get('text_pagination'), ($luckydraw_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($luckydraw_total - $this->config->get('config_limit_admin'))) ? $luckydraw_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $luckydraw_total, ceil($luckydraw_total / $this->config->get('config_limit_admin'))). '&nbsp;&nbsp;<input type="text" value="" name="pnum" size="2">&nbsp;&nbsp;<button type="button" id="button-jump" class="btn btn-primary pull-right"><i class="fa fa-arrow-right"></i>'.$this->language->get("button_jump").'</button>';

    $data = array_merge($data, $filter_data_orig);

    $data['sort'] = $sort;
    $data['order'] = $order;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/luckydraw_list.tpl', $data));
  }

  protected function getForm() {
    $data['heading_title'] = $this->language->get('heading_title');
    
    $data['text_form'] = !isset($this->request->get['luckydraw_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
    
    $data['text_yes'] = $this->language->get('text_yes');
    $data['text_no'] = $this->language->get('text_no');

    $data['button_save'] = $this->language->get('button_save');
    $data['button_cancel'] = $this->language->get('button_cancel');
    if (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    $fill_form_fileds = array('luckydraw_name'=>'', 'chance'=>'0', 'validate_method'=>'0', 'company_title'=>'0' ,'start_time'=>date('Y-m-d'), 'end_time'=>date('Y-m-d'), 'status'=>'0', 'restrict_zone_id'=>'708', 'product_number'=>'0', 'products'=>'', 'notice'=>'');

    foreach ($fill_form_fileds as $key=>$dft) {
      if (isset($this->error[$key])) {
        $data['error_' . $key] = $this->error[$key];
      } else {
        $data['error_' . $key] = '';
      }
    }

    $url = $this->buildUrlPath();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('heading_title'),
      'href' => $this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL')
    );

    $data['cancel'] = $this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL');
    
    $data['token'] = $this->session->data['token'];

    if (isset($this->request->get['luckydraw_id'])) {
      $luckydraw_info = $this->model_sale_luckydraw->getLuckydraw($this->request->get['luckydraw_id']);
      $data['luckydraw_info'] = $luckydraw_info;
      $data['export'] = $this->url->link('sale/luckydraw/export', 'token=' . $this->session->data['token'] . '&luckydraw_id=' . $luckydraw_info['luckydraw_id'], 'SSL');
    }
    
    $statuses = $this->model_sale_luckydraw->getLuckydrawStatusMap();
    $data['statuses'] = $statuses;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');
 
    $this->response->setOutput($this->load->view('sale/luckydraw_form.tpl', $data));
  }

  protected function validateDelete() {
    if (!$this->user->hasPermission('modify', 'sale/luckydraw')) {
      $this->error['warning'] = $this->language->get('error_permission');
    }

    return !$this->error;
  }

  public function autocomplete() {
    $json = array();

    if (isset($this->request->get['filter_number']) || isset($this->request->get['filter_password'])) {
      $this->load->model('sale/luckydraw');

      if (isset($this->request->get['filter_number'])) {
        $filter_number = $this->request->get['filter_number'];
      } else {
        $filter_number = '';
      }

      if (isset($this->request->get['filter_password'])) {
        $filter_password = $this->request->get['filter_password'];
      } else {
        $filter_password = '';
      }

      if (isset($this->request->get['limit'])) {
        $limit = $this->request->get['limit'];
      } else {
        $limit = 5;
      }

      $filter_data = array(
        'filter_number'  => $filter_number,
        'filter_password' => $filter_password,
        'start'        => 0,
        'limit'        => $limit
      );

      $results = $this->model_sale_luckydraw->getLuckydraws($filter_data);

      foreach ($results as $result) {
        $json[] = array(
          'luckydraw_id' => $result['luckydraw_id'],
          'number'       => $result['number'],
          'password'       => $result['password']
        );
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function luckydrawNameAutocomplete() {
    $json = array();

    if (isset($this->request->get['filter_luckydraw_name'])) {
      $this->load->model('sale/luckydraw');

      $filter_data = array(
        'filter_luckydraw_name' => $this->request->get['filter_luckydraw_name'],
        'start'       => 0,
        'limit'       => 5
      );

      $results = $this->model_sale_luckydraw->getLuckydraws($filter_data);

      foreach ($results as $result) {
        $json[] = array(
          'luckydraw_id' => $result['luckydraw_id'],
          'name'            => $result['luckydraw_name']
        );
      }
    }

    $sort_order = array();

    foreach ($json as $key => $value) {
      $sort_order[$key] = $value['name'];
    }

    array_multisort($sort_order, SORT_ASC, $json);

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function export(){
    $this->load->model('sale/luckydraw');
    $luckydraw_id = I('get.luckydraw_id');
    $results = $this->model_sale_luckydraw->getExportHitRecords($luckydraw_id);
    $headers = array('中奖编号','活动名称','订单号','支付方式','超市', '用户','电话','省市','市县','县区','地址','邮编','奖项','奖品名','业务员','抽奖日期');
    $row_keys = array('luckydraw_history_id','luckydraw_name','order_id','payment_method','shipping_company','shipping_fullname','shipping_telephone','shipping_country','shipping_zone','shipping_city','shipping_address','shipping_postcode','price_name','product_name','fullname','ldate');

    $this->load->helper('export');
    prepareDownloadExcel($results, $headers, $row_keys, 'Luckydraw');
  }
  public function sendShippingSMS(){//废弃函数
    if(I('get.luckydraw_id')){
      $luckydraw_id = I('get.luckydraw_id');
    }else{
      $luckydraw_id = 0;
    }

    $this->load->model('sale/order');
    $this->load->model('sale/luckydraw');
    $this->load->model('tool/msg_queue');
    $this->load->model('localisation/sms_tpl');
    $cnt = 0;

    $shipped_status_id = $this->model_sale_order->getShippedStatus();
    $filter_data = array('filter_order_status_id'=>$shipped_status_id,'luckydraw_id'=>$luckydraw_id);
    $shipping_infos = $this->model_sale_luckydraw->getLuckydrawBuyHistory($filter_data);
    $sms_agent = $this->config->get('config_sms_agent');
    $parent_rand_code_sms_tpl_id = $this->config->get('config_sms_luckydraw_template');
    //入短信发送消息队列
    foreach ($shipping_infos as $shipping_info) {
      $express_info = $this->model_sale_order->getOrderProducts($shipping_info['order_id']);
      $express_info = $express_info[0]; 
      $origParam = array($shipping_info['shipping_fullname'], $express_info['express_name'], $express_info['express_number']);
      $sms_tpl = $this->model_localisation_sms_tpl->getAgentSmsTpl($parent_rand_code_sms_tpl_id, $sms_agent);
      if($sms_tpl) {
        $param_map = unserialize($sms_tpl['param_map']);
        $realParam = array_combine($param_map, $origParam);
        $callback = 'tickets/luckydraw/updateLuckydrawStatus';
        $callbackParam = $shipping_info;
        $args = array(
          'phone'=>$shipping_info['shipping_telephone'],
          'templateId'=>$sms_tpl['agent_template_id'], 
          'tempParam'=>$realParam, 
          'callback'=>$callback, 
          'callbackParam'=>$callbackParam);
        $command = json_encode(array('caller'=>'sms/'.$sms_tpl['agent_code'].'/sendSms', 'params'=>$args));
        $this->model_tool_msg_queue->insertTask($command);
        //更新票券状态为短信发送中
        //$this->model_sale_giftcard->updateGiftcardStatus(4, $shipping_info['giftcard_id']);
        $cnt++;
      }
    }

    $this->session->data['success'] = $cnt . '条物流短信发送中';

    $this->response->redirect($this->url->link('sale/luckydraw', 'token=' . $this->session->data['token'] . $url, 'SSL'));
  }
}